package com.demo.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUpload {

	@RequestMapping(value = "/singleSave", method = RequestMethod.POST)
	@ResponseBody
	public String singleSave(@RequestParam("file") MultipartFile file, HttpServletRequest request)
			throws FileNotFoundException, IOException {
		String path = null;
		if (!file.isEmpty()) {
			path = request.getSession().getServletContext().getRealPath("/") + "upload/";
			// 使用StreamsAPI方式拷贝文件
			Streams.copy(file.getInputStream(), new FileOutputStream(path + file.getOriginalFilename()), true);
		}
		return "SUCCESS";

		// if (!file.isEmpty()) {
		// File fl = new File(
		// request.getSession().getServletContext().getRealPath("/") + "upload/"
		// + file.getOriginalFilename());
		// if (fl.exists()) {
		// System.out.println("文件已存在！");
		// return "Unable to upload. File is exist.";
		// }
		// try {
		// path = request.getSession().getServletContext().getRealPath("/") +
		// "upload/"
		// + file.getOriginalFilename();
		// System.out.println(path);
		// byte[] bytes = file.getBytes();
		// BufferedOutputStream buffStream = new BufferedOutputStream(new
		// FileOutputStream(new File(path)));
		// buffStream.write(bytes);
		// buffStream.close();
		// System.out.println("上存文件：" + path);
		// return "You have successfully uploaded " + path;
		// } catch (Exception e) {
		// return "You failed to upload " + path + ": " + e.getMessage();
		// }
		// } else {
		// return "Unable to upload. File is empty.";
		// }
		// }
		//
		// @RequestMapping(value = "/multipleSave", method = RequestMethod.POST)
		// @ResponseBody
		// public String multipleSave(@RequestParam("file") MultipartFile[]
		// files, HttpServletRequest request) {
		// String fileName = null;
		// String msg = "";
		// if (files != null && files.length > 0) {
		// for (int i = 0; i < files.length; i++) {
		// File file = new
		// File(request.getSession().getServletContext().getRealPath("/") +
		// "upload/"
		// + files[i].getOriginalFilename());
		// if (file.exists()) {
		// System.out.println("文件已存在！");
		// continue;
		// } else {
		// try {
		//
		// fileName = files[i].getOriginalFilename();
		// byte[] bytes = files[i].getBytes();
		// BufferedOutputStream buffStream = new BufferedOutputStream(new
		// FileOutputStream(file));
		// buffStream.write(bytes);
		// buffStream.close();
		// msg += "You have successfully uploaded " + fileName + "<br/>";
		// } catch (Exception e) {
		// return "You failed to upload " + fileName + ": " + e.getMessage() +
		// "<br/>";
		// }
		// }
		//
		// }
		// return msg;
		// } else {
		// return "Unable to upload. File is empty.";
		// }
	}

	// 基于ResponseEntity下载
	@RequestMapping("/filedownload")
	public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
		String path = request.getSession().getServletContext().getRealPath("/") + "upload/" + "Apps.zip";

		// 指定文件,必须是绝对路径
		File file = new File(path);
		// 下载浏览器响应的那个文件名
		String dfileName = file.getName();
		// 下面开始设置HttpHeaders,使得浏览器响应下载
		HttpHeaders headers = new HttpHeaders();
		// 设置响应方式
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		// 设置响应文件
		headers.setContentDispositionFormData("attachment", dfileName);
		// 把文件以二进制形式写回
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
		// HttpStatus.CREATED 状态码 最好改为 HttpStatus.OK 因为IE浏览器不支持 201状态码，下载会失败！

		// File file = new File(path);
		// byte[] body = null;
		// InputStream is = new FileInputStream(file);
		// body = new byte[is.available()];
		// is.read(body);
		// HttpHeaders headers = new HttpHeaders();
		// headers.add("Content-Disposition", "attchement;filename=" +
		// file.getName());
		// HttpStatus statusCode = HttpStatus.OK;
		// ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body,
		// headers, statusCode);
		//
		// is.close();
		// return entity;
	}

	// 通用下载
	@RequestMapping("/filedownloadcommon")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String path = request.getSession().getServletContext().getRealPath("/") + "upload/" + "Apps.zip";
		File file = new File(path);
		// 声明本次下载状态的记录对象
//		DownloadRecord downloadRecord = new DownloadRecord(file.getName(), path, request);
		// 设置响应头和客户端保存文件名
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
		// 用于记录以完成的下载的数据量，单位是byte
		long downloadedLength = 0l;
		try {
			// 打开本地文件流
			InputStream inputStream = new FileInputStream(file);
			// 激活下载操作
			OutputStream os = response.getOutputStream();

			// 循环写入输出流
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
				downloadedLength += b.length;
			}

			// 这里主要关闭。
			os.close();
			inputStream.close();
		} catch (Exception e) {
//			downloadRecord.setStatus(DownloadRecord.STATUS_ERROR);
			throw e;
		}

//		downloadRecord.setStatus(DownloadRecord.STATUS_SUCCESS);
//		downloadRecord.setEndTime(new Timestamp(System.currentTimeMillis()));
//		downloadRecord.setLength(downloadedLength);
		// 存储记录
	}
}
// File fl = new File(path);
//
// if (!fl.getParentFile().exists()) {
//
// fl.getParentFile().mkdirs();
//
// }
// file.transferTo(fl);